package main

import (
	"net"
	"log"
	"fmt"
	"time"
	"bytes"
)

func main()  {
	//绑定端口， 监听端口
	listener,err := net.Listen("tcp", ":8080")

	if err != nil {
		log.Fatal(err)
		log.Println()
	}

	//不断处理 监听 多个客户端请求
	for  {
		fmt.Println("等待客户端连接.....")

		//等待客户端 请求
		conn, err := listener.Accept() 	//阻塞
		if err != nil {
			log.Fatal(err)
		}

		go func(conn net.Conn) {

			defer conn.Close()
			fmt.Println("有客户端请求连接.", conn.RemoteAddr())

			for  {
				data := ReadSocketData(conn)
				fmt.Println(data)
				conn.Write([]byte("接收到了，hello too"))
			}

		}(conn)

	}



	time.Sleep(time.Second * 10)
}

const vilite = "\t"



func ReadSocketData(conn net.Conn) string {
	//读客户端发送的数据
	data := make([]byte, 1)
	buffer := bytes.Buffer{}
	for {
		_,err := conn.Read(data)
		if err != nil {
			log.Fatal(err)
		}
		//fmt.Println(string(data[0]))
		if string(data[0]) == vilite {
			break
		}
		buffer.Write(data[:1])
	}

	//fmt.Println(buffer.String())
	return buffer.String()
}






func ReadSocketData2(conn net.Conn) string  {

	//读取 客户端发送的数据
	bs := make([]byte, 1)		//临时读取
	buffer := bytes.Buffer{}

	for  {

		_, err := conn.Read(bs)
		if err != nil {
			log.Fatal(err)
		}

		buffer.Write(bs)

	}

	fmt.Println(buffer.String())

	return buffer.String()
}

